<template>
  <div class="products-page">
    <div class="page-header">
      <h1>Products Management</h1>
      <el-button type="primary" @click="$router.push('/products/create')">
        <n-icon size="18" style="margin-right: 0.5rem;"><AddOutline /></n-icon>
        Add Product
      </el-button>
    </div>

    <!-- Filters -->
    <el-card class="filters-card">
      <el-row :gutter="20">
        <el-col :xs="24" :sm="8">
          <el-select v-model="filters.category_id" placeholder="All Categories" clearable @change="loadProducts">
            <el-option
              v-for="cat in categories"
              :key="cat.id"
              :label="cat.name_en"
              :value="cat.id"
            />
          </el-select>
        </el-col>
        <el-col :xs="24" :sm="8">
          <el-select v-model="filters.status" placeholder="All Status" clearable @change="loadProducts">
            <el-option label="Active" :value="1" />
            <el-option label="Inactive" :value="0" />
          </el-select>
        </el-col>
        <el-col :xs="24" :sm="8">
          <el-checkbox v-model="filters.is_hot" @change="loadProducts">
            Hot Products Only
          </el-checkbox>
        </el-col>
      </el-row>
    </el-card>

    <!-- Products Table -->
    <el-card>
      <el-table v-loading="loading" :data="products" border>
        <el-table-column prop="id" label="ID" width="80" />
        <el-table-column label="Image" width="100">
          <template #default="{ row }">
            <el-image
              :src="row.main_image"
              fit="cover"
              style="width: 60px; height: 60px; border-radius: 4px;"
            />
          </template>
        </el-table-column>
        <el-table-column prop="name_en" label="Name" min-width="200" />
        <el-table-column prop="category_name_en" label="Category" width="150" />
        <el-table-column label="Hot" width="80" align="center">
          <template #default="{ row }">
            <el-tag v-if="row.is_hot" type="danger" size="small">
              <n-icon size="14"><FlameOutline /></n-icon>
            </el-tag>
            <span v-else>-</span>
          </template>
        </el-table-column>
        <el-table-column label="Status" width="100" align="center">
          <template #default="{ row }">
            <el-tag :type="row.status ? 'success' : 'info'" size="small">
              {{ row.status ? 'Active' : 'Inactive' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="display_order" label="Order" width="80" align="center" />
        <el-table-column label="Actions" width="200" align="center" fixed="right">
          <template #default="{ row }">
            <el-button size="small" @click="$router.push(`/products/edit/${row.id}`)">
              Edit
            </el-button>
            <el-popconfirm
              title="Are you sure to delete this product?"
              @confirm="deleteProduct(row.id)"
            >
              <template #reference>
                <el-button size="small" type="danger">Delete</el-button>
              </template>
            </el-popconfirm>
          </template>
        </el-table-column>
      </el-table>

      <!-- Pagination -->
      <div class="pagination-section">
        <el-pagination
          v-model:current-page="pagination.page"
          :page-size="pagination.limit"
          :total="pagination.total"
          layout="total, prev, pager, next"
          @current-change="loadProducts"
        />
      </div>
    </el-card>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { NIcon } from 'naive-ui'
import { AddOutline, FlameOutline } from '@vicons/ionicons5'
import { ElMessage } from 'element-plus'
import { productAPI, categoryAPI } from '@/api'

const loading = ref(false)
const products = ref([])
const categories = ref([])

const filters = reactive({
  category_id: null,
  status: null,
  is_hot: false
})

const pagination = reactive({
  page: 1,
  limit: 10,
  total: 0
})

const loadProducts = async () => {
  try {
    loading.value = true
    const params = {
      page: pagination.page,
      limit: pagination.limit
    }

    if (filters.category_id) params.category_id = filters.category_id
    if (filters.status !== null) params.status = filters.status
    if (filters.is_hot) params.is_hot = 1

    const response = await productAPI.getAll(params)
    if (response.success) {
      products.value = response.data
      Object.assign(pagination, response.pagination)
    }
  } catch (error) {
    console.error('Failed to load products:', error)
  } finally {
    loading.value = false
  }
}

const loadCategories = async () => {
  try {
    const response = await categoryAPI.getAll()
    if (response.success) {
      categories.value = response.data
    }
  } catch (error) {
    console.error('Failed to load categories:', error)
  }
}

const deleteProduct = async (id) => {
  try {
    await productAPI.delete(id)
    ElMessage.success('Product deleted successfully')
    loadProducts()
  } catch (error) {
    console.error('Failed to delete product:', error)
  }
}

onMounted(() => {
  loadCategories()
  loadProducts()
})
</script>

<style lang="scss" scoped>
.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 2rem;

  h1 {
    margin: 0;
    color: var(--text-primary);
  }
}

.filters-card {
  margin-bottom: 1rem;

  :deep(.el-select) {
    width: 100%;
  }
}

.pagination-section {
  display: flex;
  justify-content: center;
  margin-top: 2rem;
}
</style>

